package mstest.wechat.base.util.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import mstest.wechat.base.config.Constant;
import mstest.wechat.base.config.ResponseCode;
import mstest.wechat.base.exp.BizException;
import mstest.wechat.base.util.HttpReqUtil;
import mstest.wechat.base.util.bean.BeanUtil;

import java.util.Map;

/**
 * Project Name: wechat
 * File Name: WXUtil
 * Package Name: mstest.wechat.base.util
 * Date: 2018/8/10  10:25
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
@Slf4j
public class WXUtil {

    /**
     * 通过code获得用户信息
     * @param code
     * @return
     */
    public static Map<String,Object> getAccessToken(String code) {
        String url = Constant.token_url;
        String param = "appid="+Constant.appID+"&secret="+Constant.appSecret+"&code="+code+"&grant_type="+Constant.grant_type_auth;
        String msg = HttpReqUtil.sendGet(url, param);
        log.info("微信返回数据：" + msg);
        if("".equals(msg)) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "请求微信错误");
        }
        return JSONObject.toJavaObject(JSON.parseObject(msg), Map.class);
    }

    /**
     * 获得请求需要的accessToken
     * @param openid
     * @param accessToken
     * @param refreshToken
     * @param expireTime
     * @return
     */
    public static WXParam getRealAccessToken(String openid, String accessToken, String refreshToken, Long expireTime, Long refresExpireTime) {
        WXParam wxParam = new WXParam();
        //判断accessToken
        if(System.currentTimeMillis() > expireTime) {//失效
            //查看refreshToken是否失效
            if(System.currentTimeMillis() > refresExpireTime) {
                //需要重新登录
                return null;
            }
            //刷新accessToken
            String url = Constant.fresh_token_url;
            String param = "appid="+Constant.appID+"&grant_type="+Constant.grant_type_refresh+"&refresh_token="+refreshToken;
            String msg = HttpReqUtil.sendGet(url, param);
            log.info("微信返回数据：" + msg);
            if("".equals(msg)) {
                throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "请求微信错误");
            }
            wxParam = BeanUtil.copy(JSONObject.toJavaObject(JSON.parseObject(msg),Map.class), WXParam.class);
            return wxParam;
        }
        wxParam.setOpenid(openid);
        wxParam.setAccess_token(accessToken);
        wxParam.setRefresh_token(refreshToken);
        return wxParam;
    }
}
